import { parse } from 'qs';
import moment from 'moment';
import MD5 from 'crypto-js/md5';
import AES from 'crypto-js/aes';
import { connect } from 'dva';
import ENCUTF8 from 'crypto-js/enc-utf8';
import { LibWordArray, WordArray } from 'crypto-js';

import isObject from 'lodash/isObject';
import difference from 'lodash/difference';
import isArray from 'lodash/isArray';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import includes from 'lodash/includes';
import uniq from 'lodash/uniq';
import uniqBy from 'lodash/uniqBy';
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
import cloneDeep from 'lodash/cloneDeep';
import random from 'lodash/random';
import get from 'lodash/get';
import { getBtnPermission } from '@/services/loginServices';
import ex from 'umi/dist';

// 从这里导出 lodash 常见方法方便 webpack 摇树优化,减少打包出来的体积
export {
  difference,
  isObject,
  includes,
  isNumber,
  isString,
  isArray,
  uniq,
  debounce,
  cloneDeep,
  random,
  get,
  throttle,
  uniqBy,
};

/**
 * 获取路由参数
 */
export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

/*
 * 获取路由参数
 * */
export function getQueryVariable(name: string, url: string) {
  let href = url || window.location.href;
  let query = href.substring(href.indexOf('?') + 1);
  let vars = query.split('&');
  let obj: any = {};
  if (query.indexOf('=') > -1) {
    for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split('=');
      obj[pair[0]] = pair[1];
    }
  }
  if (name) return obj[name] || null;
  return obj;
}

/*
 * 替换11 位手机中间 4 位为星号
 * 示例 phoneNumberStar(13160807750)
 * 返回 131****7750
 * */
export function phoneNumberStar(str: string) {
  if (str === undefined) return '';
  return str.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

export function formatDate(date: any, format = 'YYYY-MM-DD HH:mm:ss') {
  if (date === undefined || date === '-') return '';
  return moment(date).format(format);
}

// 对象把 undefined 值变成空字符串
export function formDeleteEmpty(formValues: {
  [key: string]: string | number | object | any[];
}) {
  if (formValues === undefined || !isObject(formValues)) return;
  for (let i in formValues) {
    if (formValues[i] === undefined) formValues[i] = '';
  }
  return formValues;
}

// 获取下载地址的文件后缀
export function getFileExt(url: string) {
  return url.slice(url.lastIndexOf('.') + 1).toLowerCase();
}

export const formRegExp = {
  required: function(message?: string) {
    return {
      required: true,
      message: message || '该字段为必填项',
    };
  },
  string: function(message?: string) {
    return {
      type: 'string',
      message: message || '必须为字符串',
    };
  },
  number: function(message?: string) {
    return {
      pattern: /^[0-9]*$/,
      message: message || '必须为数值类型',
    };
  },
  url: function(message?: string) {
    return {
      type: 'url',
      message: message || '请输入http:// 或者 https:// 开头的网址',
    };
  },
  phone: function(message?: string) {
    return {
      pattern: /^1[3456789]\d{9}$/,
      message: message || '请输入正确手机号!',
    };
  },
  email: function(message?: string) {
    return {
      pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: message || '请输入正确邮箱格式!',
    };
  },
  range: function(min: number, max: number, message?: string) {
    return {
      min,
      max,
      message: message || `字段最小长度为${min}位,最大长度为${max}位`,
    };
  },
  min: function(length: number, message?: string) {
    return {
      min: length,
      message: message || `最小长度为${length}位`,
    };
  },
  max: function(length: number, message?: string) {
    return {
      max: length,
      message: message || `最大长度为${length}位`,
    };
  },
  len: function(length: number, message?: string) {
    return {
      len: length,
      message: message || `长度必须为${length}位`,
    };
  },
  length18CarNumber: function(message?: string) {
    return {
      pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:(?:0[1-9])|(?:1[0-2]))(?:(?:[0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: message || '请输入正确身份证号码!',
    };
  },
};

export const encryption = {
  salt1: 'heh',
  iv: 'da',
  MD5: function(s: string | number) {
    return MD5(s.toString()).toString();
  },
  AESEncrypt: function(s: string | LibWordArray) {
    return AES.encrypt(s, this.salt1, { iv: this.iv }).toString();
  },
  AESDecrypt: function(s: string | WordArray) {
    return AES.decrypt(s, this.salt1, { iv: this.iv }).toString(ENCUTF8);
  },
};

export function btnPermission(path: string, operation: any) {
  // return true;
  if (path.charAt(path.length - 1) === '/') {
    path = path.substring(0, path.length - 1);
  }
  if (hehLocalStorage.hasItem(path) || hehLocalStorage.hasItem(path + '/')) {
    const arr = hehLocalStorage.getItem(path);
    if (isArray(operation)) {
      return difference(operation, arr).length !== operation.length;
    } else if (isString(operation)) {
      return arr.includes(operation);
    }
  }
  return false;
}

export function formatDateTimeStamp(date: string | number, type?: any) {
  if (date === undefined || date === '') return;
  if (type === 'start') {
    return moment(moment(date).format('YYYY-MM-DD 00:00:00')).valueOf();
  }
  if (type === 'end') {
    return moment(moment(date).format('YYYY-MM-DD 23:59:59')).valueOf();
  }
  if (type === undefined) {
    return moment(moment(date).format('YYYY-MM-DD HH:mm:ss')).valueOf();
  }
  return '';
}

/**
 * 判断所有loading是否都为 true
 */
export function mergeLoading(...args: any[]) {
  let loadingStatus = false;
  args.forEach((status: boolean) => {
    if (status) {
      loadingStatus = true;
    }
  });
  return loadingStatus;
}

export const hehLocalStorage = {
  setItem(key: string, value: string): void {
    if (process.env.NODE_ENV === 'production') {
      localStorage.setItem(key, encryption.AESEncrypt(JSON.stringify(value)));
    } else {
      localStorage.setItem(key, JSON.stringify(value));
    }
  },
  getItem(key: string) {
    if (process.env.NODE_ENV === 'production') {
      if (localStorage.getItem(key) !== null) {
        return JSON.parse(
          encryption.AESDecrypt(localStorage.getItem(key) || ''),
        );
      } else {
        return undefined;
      }
    } else {
      if (localStorage.getItem(key) !== null) {
        return JSON.parse(localStorage.getItem(key) || '');
      } else {
        return undefined;
      }
    }
  },
  hasItem(key: any) {
    return localStorage.getItem(key) !== null;
  },
};

export function downloadFile(record: any, fileName?: any) {
  if (fileName === undefined) {
    let url = record;
    let index = url.lastIndexOf('/');
    fileName = url.substring(index + 1, url.length);
  }
  var request = new XMLHttpRequest();
  request.responseType = 'blob'; //定义响应类型
  request.open('GET', record);
  request.onload = function() {
    var url = window.URL.createObjectURL(this.response);
    var a = document.createElement('a');
    document.body.appendChild(a);
    a.href = url;
    a.download = fileName;
    a.click();
  };
  request.send();
}

export function diffSubmitData(old: any, newData: any) {
  let updateData: any = {};
  console.log(old, newData);
  for (let i in newData) {
    if (old[i]) {
      if (old[i] !== newData[i]) {
        if (isObject(old[i]) && old[i].$D) {
          if (formatDate(old[i]) !== formatDate(newData[i])) {
            updateData[i] = newData[i];
          }
        } else {
          updateData[i] = newData[i];
        }
      } else {
        if (i === 'parentId') {
          updateData['parentId'] = old['parentId'];
        }
      }
    } else {
      updateData[i] = newData[i];
    }
  }
  // for (let i in updateData){
  //   if(updateData[i] === null || updateData[i] === 'null'){
  //     updateData[i] = ''
  //   }
  // }
  return updateData;
}
